package com.scoremg.api;

import cn.hutool.core.util.ArrayUtil;
import com.scoremg.annotation.GlobalInterceptor;
import com.scoremg.entity.dto.AddUserInfoDto;
import com.scoremg.entity.dto.WebSessionUserDto;
import com.scoremg.entity.enums.ResponseCodeEnum;
import com.scoremg.entity.enums.RoleTypeEnums;
import com.scoremg.entity.po.UserInfo;
import com.scoremg.entity.query.LayuiSearchQuery;
import com.scoremg.entity.query.UserInfoQuery;
import com.scoremg.entity.vo.LayuiResultVO;
import com.scoremg.entity.vo.PaginationResultVO;
import com.scoremg.entity.vo.ResponseVO;
import com.scoremg.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;

import com.scoremg.service.UserInfoService;

@RestController
@RequestMapping("/admin")
public class UserInfoController extends ABaseController {

	@Resource
	private UserInfoService userInfoService;

	/**
	 * 分页查询
	 */
	@RequestMapping("/loadUserList")
	@GlobalInterceptor(checkAdmin = true)
	public LayuiResultVO loadDataList(@RequestBody LayuiSearchQuery<UserInfoQuery> query) {
		UserInfoQuery infoQuery = new UserInfoQuery();
		infoQuery.setPageNo(query.getPage());
		infoQuery.setPageSize(query.getLimit());
		BeanUtils.copyProperties(query.getData(), infoQuery);
		infoQuery.setOrderBy("create_time desc");
		infoQuery.setRoleType(RoleTypeEnums.STUDENT.getType());
		PaginationResultVO<UserInfo> listByPage = userInfoService.findListByPage(infoQuery);
		LayuiResultVO<UserInfo> layuiResultVO = getSuccessLayuiResultVO(listByPage.getList());
		layuiResultVO.setCount(listByPage.getTotalCount());
		return layuiResultVO;
	}

	/**
	 * 新增
	 */
	@RequestMapping("/saveInfo")
	@GlobalInterceptor(checkAdmin = true)
	public ResponseVO saveInfo(AddUserInfoDto bean) {
		this.userInfoService.saveInfo(bean);
		return getSuccessResponseVO(null);
	}

	/**
	 * 删除用户信息
	 * @param userId
	 * @return
	 */
	@RequestMapping("/delInfo")
	@GlobalInterceptor(checkAdmin = true)
	public ResponseVO delInfo(HttpSession session,
							  @NotEmpty String userId) {

		// 不能删除自己
		String[] idArray = userId.split(",");
		WebSessionUserDto webSessionUserDto = getUserInfoFromSession(session);
		if (ArrayUtil.contains(idArray, webSessionUserDto.getUserId())) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		this.userInfoService.delInfoBatch(idArray);
		return getSuccessResponseVO(null);
	}

	// TODO 重置密码
}